package com.serialization.demo2;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

import com.serialization.demo1.Worm;

/**
 * Externalizable的替代方案
 * 
 * @author Administrator
 *
 */
public class SerialCtl implements Serializable {

	private String a;
	private transient String b;

	public SerialCtl(String aa, String bb) {
		a = "Not Transient:" + aa;
		b = "Transient:" + bb;
	}

	public String toString() {
		return a + "\n" + b;
	}

	// 实现自己的writeObject，并且方法签名必须是下面这样，这样在调用ObjectOutputStream的writeObject时，会先调用被序列化对象的writeObject方法
	private void writeObject(ObjectOutputStream stream) throws IOException {
		// 调用默认的序列化方法，但不会序列化transient字段
		stream.defaultWriteObject();
		// 自己序列化transient字段
		stream.writeObject(b);
	}

	private void readObject(ObjectInputStream stream) throws IOException,
			ClassNotFoundException {
		// 调用默认的序列化方法，但不会序列化transient字段
		stream.defaultReadObject();
		// 自己序列化transient字段
		b = (String) stream.readObject();
	}

	public static void main(String[] args) throws IOException,
			ClassNotFoundException {
		SerialCtl sc = new SerialCtl("Test1", "Test2");
		System.out.println("before:" + sc);

		ByteArrayOutputStream buf = new ByteArrayOutputStream();
		ObjectOutputStream o = new ObjectOutputStream(buf);
		o.writeObject(sc);
		o.flush();

		ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(
				buf.toByteArray()));
		SerialCtl sc2 = (SerialCtl) in.readObject();
		System.out.println("before:" + sc2);
	}

}
